using AdmissionQA.Application.Common;
using AdmissionQA.Application.Dtos.CampusLife;
using AdmissionQA.Application.ServiceInterfaces;
using AdmissionQA.Domain.Entities;
using AdmissionQA.Domain.Repositorys;
using Microsoft.Extensions.Logging;

namespace AdmissionQA.Application.Services;

/// <summary>
/// 校园生活服务实现
/// </summary>
public class CampusLifeServices(IRepository<CampusLife> repository, ILogger<CampusLifeServices> logger, ITextEmbeddingService embeddingService)
    : ICampusLifeServices
{
    private readonly IRepository<CampusLife> _repository = repository;
    private readonly ILogger<CampusLifeServices> _logger = logger;
    private readonly ITextEmbeddingService _embeddingService = embeddingService;

    /// <summary>
    /// 批量创建校园生活信息
    /// </summary>
    /// <param name="campusLives">校园生活信息列表</param>
    /// <returns>创建结果</returns>
    public async Task<Result<string>> CreateCampusLivesAsync(CampusLivesDto campusLives)
    {
        var livesToCreate = campusLives
            .CampusLives.Select(item => CampusLife.CreateCampusLife(item.Category))
            .Where(item => item != null)
            .Select(item => item!)
            .ToList();

        if (livesToCreate.Count == 0)
        {
            _logger.LogWarning("批量创建校园生活信息失败：没有有效的信息");
            return Result<string>.Fail("没有有效的校园生活信息可以创建");
        }

        await _repository.CreateRangeAsync(livesToCreate);
        _logger.LogInformation("批量创建校园生活信息成功，数量：{Count}", livesToCreate.Count);
        return Result<string>.Success("创建成功");
    }

    /// <summary>
    /// 创建校园生活信息
    /// </summary>
    /// <param name="campusLife">校园生活信息</param>
    /// <returns>创建结果</returns>
    public async Task<Result<string>> CreateCampusLifeAsync(CampusLifeDto campusLife)
    {
        var life = CampusLife.CreateCampusLife(campusLife.Category);
        if (life == null)
        {
            _logger.LogWarning("创建校园生活信息失败，参数：{@CampusLife}", campusLife);
            return Result<string>.Fail("创建校园生活信息失败");
        }
        var content = campusLife.Category + " " + (campusLife.Description ?? "");
        life.Embedding = _embeddingService.GetVector(content);
        await _repository.CreateAsync(life);
        _logger.LogInformation("创建校园生活信息成功，类别：{Category}", campusLife.Category);
        return Result<string>.Success("创建成功");
    }

    /// <summary>
    /// 批量删除校园生活信息
    /// </summary>
    /// <param name="ids">校园生活信息ID列表</param>
    /// <returns>删除结果</returns>
    public async Task<Result<string>> DeleteCampusLivesAsync(IEnumerable<Guid> ids)
    {
        // 并行获取所有校园生活信息
        var tasks = ids.Select(id => _repository.GetByIdAsync(id));
        var lives = await Task.WhenAll(tasks);

        // 过滤掉 null 值并转换为非空类型
        var validLives = lives.OfType<CampusLife>().ToList();

        // 检查是否有有效的校园生活信息
        if (validLives.Count == 0)
        {
            _logger.LogWarning("批量删除校园生活信息失败：未找到任何信息，ids={@Ids}", ids);
            return Result<string>.Fail("没有找到校园生活信息");
        }

        // 调用 Delete 方法标记为删除
        foreach (var life in validLives)
        {
            if (!life.Delete())
            {
                _logger.LogWarning("批量删除校园生活信息时，信息已被删除，id={Id}", life.Id);
                return Result<string>.Fail($"校园生活信息 {life.Id} 已经被删除");
            }
        }

        // 更新所有有效的校园生活信息
        await _repository.UpdateRangeAsync(validLives);
        _logger.LogInformation("批量删除校园生活信息成功，数量：{Count}", validLives.Count);

        return Result<string>.Success("删除成功");
    }

    /// <summary>
    /// 删除校园生活信息
    /// </summary>
    /// <param name="id">校园生活信息ID</param>
    /// <returns>删除结果</returns>
    public async Task<Result<string>> DeleteCampusLifeAsync(Guid id)
    {
        var life = await _repository.GetByIdAsync(id);
        if (life == null)
        {
            _logger.LogWarning("删除校园生活信息失败：未找到信息，id={Id}", id);
            return Result<string>.Fail("没有找到校园生活信息");
        }
        if (!life.Delete())
        {
            _logger.LogWarning("删除校园生活信息失败：信息已被删除，id={Id}", id);
            return Result<string>.Fail("校园生活信息已经被删除");
        }
        await _repository.UpdateAsync(life);
        _logger.LogInformation("删除校园生活信息成功，id={Id}", id);
        return Result<string>.Success("删除成功");
    }

    /// <summary>
    /// 根据ID获取校园生活信息
    /// </summary>
    /// <param name="id">校园生活信息ID</param>
    /// <returns>校园生活信息</returns>
    public async Task<Result<CampusLife>> GetCampusLifeByIdAsync(Guid id)
    {
        var life = await _repository.GetByIdAsync(id);
        if (life == null)
        {
            return Result<CampusLife>.Fail("没有找到校园生活信息");
        }
        return Result<CampusLife>.Success(life);
    }

    /// <summary>
    /// 获取校园生活信息数量
    /// </summary>
    /// <returns>校园生活信息数量</returns>
    public async Task<int> GetCampusLifeCountAsync()
    {
        return await _repository.GetCountAsync();
    }

    /// <summary>
    /// 获取所有校园生活信息
    /// </summary>
    /// <returns>校园生活信息列表</returns>
    public async Task<Result<IEnumerable<CampusLife>>> GetAllCampusLivesAsync()
    {
        var lives = await _repository.GetAllAsync();
        return Result<IEnumerable<CampusLife>>.Success(lives);
    }

    /// <summary>
    /// 分页获取校园生活信息
    /// </summary>
    /// <param name="pageIndex">页码</param>
    /// <param name="pageSize">页大小</param>
    /// <returns>分页结果</returns>
    public async Task<Result<IEnumerable<CampusLife>>> GetPagedCampusLivesAsync(
        int pageIndex = 0,
        int pageSize = 10
    )
    {
        var lives = await _repository.GetPagedAsync(pageIndex, pageSize);
        return Result<IEnumerable<CampusLife>>.Success(lives);
    }

    /// <summary>
    /// 根据类别搜索校园生活信息
    /// </summary>
    /// <param name="category">类别</param>
    /// <returns>匹配的校园生活信息列表</returns>
    public async Task<Result<IEnumerable<CampusLife>>> SearchCampusLivesByCategoryAsync(
        string category
    )
    {
        var lives = await _repository.GetListConditionAsync(item =>
            item.Category.Contains(category)
        );
        return Result<IEnumerable<CampusLife>>.Success(lives);
    }

    /// <summary>
    /// 更新校园生活信息
    /// </summary>
    /// <param name="id">校园生活信息ID</param>
    /// <param name="campusLife">校园生活信息</param>
    public async Task<Result<string>> UpdateCampusLifeAsync(Guid id, CampusLifeDto campusLife)
    {
        var life = await _repository.GetByIdAsync(id);
        if (life == null)
        {
            _logger.LogWarning("更新校园生活信息失败：未找到信息，id={Id}", id);
            return Result<string>.Fail("没有找到校园生活信息");
        }
        life.UpdateCampusLife(campusLife.Category, campusLife.Description);
        var content = campusLife.Category + " " + (campusLife.Description ?? "");
        life.Embedding = _embeddingService.GetVector(content);
        await _repository.UpdateAsync(life);
        _logger.LogInformation("更新校园生活信息成功，id={Id}", id);
        return Result<string>.Success("更新成功");
    }

    public async Task<Result<IEnumerable<CampusLife>>> SearchCampusLifesByEmbeddingAsync(string text, int topK = 5)
    {
        var queryEmbedding = _embeddingService.GetVector(text);
        var all = await _repository.GetAllAsync();
        var withScore = all.Where(x => x.Embedding != null)
            .Select(x => new { Entity = x, Score = CosineSimilarity(queryEmbedding, x.Embedding!) })
            .OrderByDescending(x => x.Score)
            .Take(topK)
            .Select(x => x.Entity)
            .ToList();
        return Result<IEnumerable<CampusLife>>.Success(withScore);
    }
    private static float CosineSimilarity(float[] v1, float[] v2)
    {
        if (v1 == null || v2 == null || v1.Length != v2.Length) return 0f;
        float dot = 0, norm1 = 0, norm2 = 0;
        for (int i = 0; i < v1.Length; i++)
        {
            dot += v1[i] * v2[i];
            norm1 += v1[i] * v1[i];
            norm2 += v2[i] * v2[i];
        }
        if (norm1 == 0 || norm2 == 0) return 0f;
        return dot / (float)(Math.Sqrt(norm1) * Math.Sqrt(norm2));
    }
}
